package com.yingran.common;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.RxLifecycle;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.trello.rxlifecycle2.android.RxLifecycleAndroid;
import com.yingran.common.util.DateUtil;
import com.yingran.common.util.PermissionUtils;
import com.yingran.common.util.ToastManager;
import com.yingran.common.view.HeadBar;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;


/**
 * Created by WHFP on 2018/3/10.
 * Copyright © 2018年 WHFP. All rights reserved.
 */

public class CommonBaseFragment extends Fragment implements LifecycleProvider<FragmentEvent> {
    private final BehaviorSubject<FragmentEvent> lifecycleSubject = BehaviorSubject.create();
    private ProgressDialog progressDialog;
    private long dialogStartShowTime;
    private HeadBar baseFragmentHeadBar;
    protected Handler handler = new Handler(Looper.getMainLooper());
    protected Context context;
    protected CommonBaseFragment fragment;
    private Unbinder unbinder;
    protected Activity activity;
    private ViewGroup baseRootLayout;

    protected boolean isEmpty(String msg) {
        return TextUtils.isEmpty(msg);
    }

    protected boolean isNotEmpty(String msg) {
        return !TextUtils.isEmpty(msg);
    }

    protected boolean isSame(String msgL, String msgR) {
        return TextUtils.equals(msgL, msgR);
    }

    protected boolean isNotSame(String msgL, String msgR) {
        return !TextUtils.equals(msgL, msgR);
    }


    public void jump2Activity(Class cls) {
        if (isFastClick()) {
            return;
        }
        if (cls != null) {
            Intent intent = new Intent(getContext(), cls);
            startActivity(intent);
        }
    }

    public void jump2Activity(Intent intent) {
        if (isFastClick()) {
            return;
        }
        if (intent != null) {
            startActivity(intent);
        }
    }

    public void jump2Activity(Intent intent, int requestCode) {
        if (isFastClick()) {
            return;
        }
        if (intent != null) {
            startActivityForResult(intent, requestCode);
        }
    }

    private long lastClickTime;

    protected boolean isFastClick() {
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) < 1000) {
            lastClickTime = curClickTime;
            return true;
        }
        lastClickTime = curClickTime;
        return false;
    }


    public void jump2Activity(Class cls, int requestCode) {
        if (isFastClick()) {
            return;
        }
        if (cls != null) {
            Intent intent = new Intent(getContext(), cls);
            startActivityForResult(intent, requestCode);
        }
    }

    protected enum Title {
        None,
        Float,
        Inner
    }


    protected Title titleType() {
        return Title.None;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (baseFragmentHeadBar == null) {
            baseFragmentHeadBar = new HeadBar(context);
        }
        Title title = titleType();
        if (null == baseRootLayout) {
            if (title == Title.Inner) {
                baseRootLayout = new LinearLayout(context);
                LinearLayout tempLayout = (LinearLayout) baseRootLayout;
                tempLayout.setOrientation(LinearLayout.VERTICAL);
            } else if (title == Title.Float) {
                baseRootLayout = new RelativeLayout(context);
            } else {
                baseRootLayout = new FrameLayout(context);
            }
            baseRootLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        }
        baseRootLayout.removeAllViews();
        if (title != Title.None) {
            baseRootLayout.addView(baseFragmentHeadBar, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        }
        View view = onCreateView(inflater, baseRootLayout);
        if (view != null) {
            baseRootLayout.addView(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            if (title == Title.Float) {
                baseFragmentHeadBar.bringToFront();
            }
        }
        unbinder = ButterKnife.bind(this, baseRootLayout);
        return baseRootLayout;
    }

    public boolean fragmentCanGoBack() {
        return false;
    }


    protected HeadBar getHeadBar() {
        return baseFragmentHeadBar;
    }

    protected View onCreateView(LayoutInflater inflater, ViewGroup container) {
        return null;
    }


    protected void showLog(Object o) {
        if (o == null) {
            LogTool.e("Log-> no ");
            return;
        }
        LogTool.e("Log->  " + o.toString());
    }

    public void showToast(String msg) {
        ToastManager.getInstance().show(msg);
    }

    public void showWaiting(String msg) {
//        String tipMsg = msg;
//        if (progressDialog == null) {
//            progressDialog = new StatusDialog(context);
//        }
//        if (isEmpty(tipMsg)) {
//            tipMsg = "请稍后...";
//        }
//        dialogStartShowTime = DateUtil.getCurrentTimeInMillis();
//        progressDialog.showLoading(tipMsg);
    }

    public void showWaiting() {
        showWaiting("请稍后...");
    }

    public void closeWaiting() {
        long rangeTime = DateUtil.getCurrentTimeInMillis() - dialogStartShowTime;
        if (rangeTime <= 1000) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                }
            }, 1000 - rangeTime);
        } else {
            if (progressDialog != null) {
                progressDialog.dismiss();
            }
        }
    }

    public void addFragment(int containerViewId, Fragment fragment) {
        if (fragment != null && !fragment.isAdded()) {
            getChildFragmentManager().beginTransaction().add(containerViewId, fragment).commitAllowingStateLoss();
        }
    }

    public void showFragment(Fragment fragment) {
        if (fragment != null && fragment.isAdded())
            getChildFragmentManager().beginTransaction().show(fragment).commitAllowingStateLoss();
    }

    public void replaceFragment(int layoutId, Fragment fragment) {
        if (fragment != null)
            getChildFragmentManager().beginTransaction().replace(layoutId, fragment).commitAllowingStateLoss();
    }

    public void hideFragment(Fragment fragment) {
        if (fragment != null && fragment.isAdded())
            getChildFragmentManager().beginTransaction().hide(fragment).commitAllowingStateLoss();
    }

    @Override
    @NonNull
    @CheckResult
    public final Observable<FragmentEvent> lifecycle() {
        return lifecycleSubject.hide();
    }

    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindUntilEvent(@NonNull FragmentEvent event) {
        return RxLifecycle.bindUntilEvent(lifecycleSubject, event);
    }

    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindToLifecycle() {
        return RxLifecycleAndroid.bindFragment(lifecycleSubject);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
        this.fragment = this;
        this.activity = (Activity) context;
        lifecycleSubject.onNext(FragmentEvent.ATTACH);
    }

    @Nullable
    @Override
    public Context getContext() {
        return context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        lifecycleSubject.onNext(FragmentEvent.CREATE);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        lifecycleSubject.onNext(FragmentEvent.CREATE_VIEW);
    }

    @Override
    public void onStart() {
        super.onStart();
        lifecycleSubject.onNext(FragmentEvent.START);
    }

    @Override
    public void onResume() {
        super.onResume();
        lifecycleSubject.onNext(FragmentEvent.RESUME);
    }

    @Override
    public void onPause() {
        lifecycleSubject.onNext(FragmentEvent.PAUSE);
        super.onPause();
    }

    @Override
    public void onStop() {
        lifecycleSubject.onNext(FragmentEvent.STOP);
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        lifecycleSubject.onNext(FragmentEvent.DESTROY_VIEW);
        super.onDestroyView();
        if (unbinder != null) {
            unbinder.unbind();
        }
    }

    @Override
    public void onDestroy() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }

        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        lifecycleSubject.onNext(FragmentEvent.DESTROY);
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        lifecycleSubject.onNext(FragmentEvent.DETACH);
        super.onDetach();
    }

    public boolean onBackPressed() {
        return true;
    }

    protected void toSetting(int requestCode) {
        PermissionUtils.toAppSetting(CommonBaseFragment.this, requestCode, activity.getPackageName());
    }

    protected void showPermissionDialog(final int requestCode, String msg) {
        NoticeDialog noticeDialog = new NoticeDialog(context);
        noticeDialog.setMsg(msg);
        noticeDialog.setCancelable(false);
        noticeDialog.setEnterClickListener(new NoticeDialog.EnterClickListener() {
            @Override
            public void enter(BaseDialog dialog) {
                dialog.dismiss();
                toSetting(requestCode);
            }
        });
        noticeDialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        onResult4Permission(requestCode);
    }

    protected void onResult4Permission(int requestCode) {

    }

    protected void hideSoftInput() {
        try {
            View view = getActivity().getCurrentFocus();
            if (view == null)
                view = new View(getContext());
            InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
            if (imm == null)
                return;
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



}
